package cn.xfdzx.android.apps.shop.activity;


import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.net.Uri;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.luck.picture.lib.tools.ToastUtils;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMMin;

import org.greenrobot.eventbus.EventBus;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cn.xfdzx.android.apps.shop.R;
import cn.xfdzx.android.apps.shop.activity.login.OneLoginMainActivity;
import cn.xfdzx.android.apps.shop.adapter.DetailsAdapter;
import cn.xfdzx.android.apps.shop.adapter.XFDShopAddCarAdapter;
import cn.xfdzx.android.apps.shop.apps.Constants;
import cn.xfdzx.android.apps.shop.base.BaseMvpActivity;
import cn.xfdzx.android.apps.shop.bean.ConfirmGoodBeen;
import cn.xfdzx.android.apps.shop.bean.DetailsBean;
import cn.xfdzx.android.apps.shop.bean.MoreGoodsBean;
import cn.xfdzx.android.apps.shop.bean.ShopCarListBeen;
import cn.xfdzx.android.apps.shop.bean.ShopRemakeListMarketBean;
import cn.xfdzx.android.apps.shop.bean.XFDGoodsDetailsBeen;
import cn.xfdzx.android.apps.shop.contract.TotalNumListener;
import cn.xfdzx.android.apps.shop.contract.XFDGoodsDetailsContract;
import cn.xfdzx.android.apps.shop.evenbus.HomeFlushCarData;
import cn.xfdzx.android.apps.shop.presenter.XFDGoodsDetailsPresenter;
import cn.xfdzx.android.apps.shop.util.EmptyUtil;
import cn.xfdzx.android.apps.shop.util.ProgressDialog;
import cn.xfdzx.android.apps.shop.util.ShopCarPopupWindow;
import cn.xfdzx.android.apps.shop.util.StatusBarUtil;
import cn.xfdzx.android.apps.shop.util.Utils;
import cn.xfdzx.android.apps.shop.util.UtilsData;
import cn.xfdzx.android.apps.shop.view.ShoppingCartAnimationView;
import cn.xfdzx.android.apps.shop.widget.ChooseShareTypeDialog;

import static cn.xfdzx.android.apps.shop.apps.Constants.APP_TOKEN;

/**
 * 新发地商品详情
 */
public class XFDGoodsDeatailsActivity extends BaseMvpActivity<XFDGoodsDetailsPresenter> implements XFDGoodsDetailsContract.View {

    @BindView(R.id.rv_goods_details)
    LRecyclerView rvGoodsDetails;
    @BindView(R.id.tv_title_1)
    TextView tvTitle1;
    @BindView(R.id.tv_title_2)
    TextView tvTitle2;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.tv_add_car_bg)
    TextView tvAddCarBg;//立即购物
    @BindView(R.id.tv_car_num)
    TextView tvCarNum;
    @BindView(R.id.ll_state)
    LinearLayout llState;
    @BindView(R.id.iv_details_share)
    ImageView ivDetailsShare;
    @BindView(R.id.tv_add_car)
    TextView tvAddCar;//添加到购物车
    @BindView(R.id.iv_shop_car)
    ImageView ivShopCar;//右上角购物车
    @BindView(R.id.tv_shop)
    TextView tvShop;
    @BindView(R.id.tv_phone)
    TextView tvPhone;

    private DetailsAdapter detailsAdapter;
    private List<DetailsBean> list;

    private int item1 = 0;
    private int item2 = 0;
    private float totaldy;
    private float mRecyclerFactor;
    private boolean is_one = true;

    private ShopCarPopupWindow add_car_bg_PW;
    private ShopCarPopupWindow preferential_PW;
    private ShopCarPopupWindow service_PW;
    private ShopCarPopupWindow shard_PW;
    private RelativeLayout.LayoutParams item_bar;
    private int totalNum = 0;
    private XFDGoodsDetailsBeen.DataBean dataBean;

    private boolean dark = false;//顶部状态栏颜色
    private int is_new = 0;//是否是直接购买
    private Activity mContext;
    private List<MoreGoodsBean.DataBean> data;
    private Bitmap bitmap;
    private String good_id;

    @Override
    public int getLayoutId() {
        return R.layout.activity_xfdgoods_deatails;
    }

    @Override
    public void initView() {
        mContext = this;
        StatusBarUtil.setLightStatusBar(this, false, true);
        initHigh();
        mPresenter = new XFDGoodsDetailsPresenter();
        mPresenter.attachView(this);
        good_id = getIntent().getStringExtra("good_id");
        mPresenter.initData(good_id);
//        mPresenter.initData("55");
        if (UtilsData.getPreference(this, "carCount").getInteger("car_pf_count") == 0) {
            tvCarNum.setVisibility(View.GONE);
        } else {
            tvCarNum.setVisibility(View.VISIBLE);
        }
        tvCarNum.setText(UtilsData.getPreference(this, "carCount").getInteger("car_pf_count") + "");

        DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        mRecyclerFactor = displayMetrics.widthPixels / 5 * 2;
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);

        detailsAdapter = new DetailsAdapter(this,mPresenter,good_id);
        list = new ArrayList<>();
        for (int i = 0; i < 2; i++) {
            DetailsBean bean = new DetailsBean();
            bean.setType(i + 1);
            list.add(bean);
        }
        detailsAdapter.setDataList(list);
        detailsAdapter.setListener(new DetailsAdapter.OnItemHeightListener() {
            @Override
            public void setOnItemHeightListener(int height, int type) {
                if (height != 0) {
                    if (type == 1001) {
                        item1 = height;
                    } else if (type == 1002) {
                        item2 = item1 + height;
                    }
                }
            }

            @Override
            public void setOnPreferential(XFDGoodsDetailsBeen.DataBean.StoreInfoBean.PreferentialActivitiesBean bean) {
                if (preferential_PW == null) {
                    preferential_PW = new ShopCarPopupWindow(mContext, R.layout.pw_preferential);
                    ((TextView) preferential_PW.getRootView().findViewById(R.id.tv_preferential_title)).setText(bean.getTitle());
                    ((TextView) preferential_PW.getRootView().findViewById(R.id.tv_preferential_content)).setText(bean.getContent());
                    preferential_PW.getRootView().findViewById(R.id.tv_shut_down).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            preferential_PW.shareClose();
                        }
                    });
                }
                preferential_PW.showPopupWindow();
            }

            @Override
            public void setOnService() {
                if (null != dataBean) {
                    if (service_PW == null) {
                        service_PW = new ShopCarPopupWindow(mContext, R.layout.pw_service);
                        ((TextView) service_PW.getRootView().findViewById(R.id.tv_service_title)).setText(dataBean.getStoreInfo().getGoods_ensures().getTitle());
                        ((TextView) service_PW.getRootView().findViewById(R.id.tv_service_content)).setText(dataBean.getStoreInfo().getGoods_ensures().getContent());

                        service_PW.getRootView().findViewById(R.id.tv_shut_down).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                service_PW.shareClose();
                            }
                        });
                    }
                    service_PW.showPopupWindow();
                }
            }

            @Override
            public void setFinsh() {
                finish();
            }

            @Override
            public void showAdddPW() {
                if (dataBean.getProductValue().size()>1) {
//                    showPW();
                }
            }
        });

        /**
         * 收藏事件回调
         * **/
        detailsAdapter.setCollectionListener(new DetailsAdapter.OnCollectionClickListener() {
            @Override
            public void setCollectionClickListener(String type, int goodsId) {
                if (EmptyUtil.isNotEmpty(APP_TOKEN)){
                    if (type.equals("1")){//收藏
                        Map<String,Object> map = new HashMap<>();
                        map.put("category","goods");
                        map.put("id",goodsId);
                        mPresenter.getGoodsCollection(map);
                    }else {
                        Map<String,Object> map = new HashMap<>();
                        map.put("category","goods");
                        map.put("id",goodsId);
                        mPresenter.getGoodsCancleCollection(map);
                    }
                }else {
                    Intent intent = new Intent(XFDGoodsDeatailsActivity.this,OneLoginMainActivity.class);
                    startActivity(intent);
                }

            }
        });
        LRecyclerViewAdapter adapter = new LRecyclerViewAdapter(detailsAdapter);

        rvGoodsDetails.setLayoutManager(linearLayoutManager);
        rvGoodsDetails.setPullRefreshEnabled(false);

        //        设置渐变的主要代码
        rvGoodsDetails.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recycler, int dx, int dy) {
                super.onScrolled(recycler, dx, dy);
                //滑动的距离
                totaldy += dy;
                if (totaldy < item1) {
                    if (!is_one) {
                        is_one = true;
                        tvTitle1.setTextColor(getResources().getColor(R.color.color_02C557));
                        tvTitle2.setTextColor(getResources().getColor(R.color.color_333333));
                    }
                }
//                else if (totaldy > item1 && totaldy < item2) {
//                    title2();
//                }
                else if (totaldy > item2) {
                    if (is_one) {
                        is_one = false;
                        tvTitle1.setTextColor(getResources().getColor(R.color.color_333333));
                        tvTitle2.setTextColor(getResources().getColor(R.color.color_02C557));
                    }
                }
                //当滑动的距离 <= toolbar高度的时候，改变Toolbar背景色的透明度，达到渐变的效果
                if (totaldy <= mRecyclerFactor) {
                    float scale = (float) totaldy / mRecyclerFactor;
                    if (totaldy > 150) {
                        rlTitle.setAlpha(scale);
                        llState.setAlpha(scale);

                        if (dark) {
                            dark = false;
                            StatusBarUtil.setLightStatusBar(mContext, true, true);
                        }
                    } else {
                        rlTitle.setAlpha(0);
                        llState.setAlpha(0);
                        if (!dark) {
                            dark = true;
                            StatusBarUtil.setLightStatusBar(mContext, false, true);
                        }

                    }
                } else {
                    rlTitle.setAlpha(1);
                    llState.setAlpha(1);
                }

            }
        });
        rvGoodsDetails.setAdapter(adapter);
    }

    /**
     *
     */
    private void initDate() {
        Map<String, Object> map = new HashMap<>();
        map.put("store_id", dataBean.getShopInfo().getId());
        map.put("page", 1);
        map.put("limit", 6);
        mPresenter.getStoreGoodsList(map);

    }

    private void initHigh() {
        item_bar = (RelativeLayout.LayoutParams) llState.getLayoutParams();
        item_bar.height = StatusBarUtil.getStatusBarHeight(this);
        llState.setLayoutParams(item_bar);
    }

    @Override
    public void onStart() {
        super.onStart();
        //开始轮播
        detailsAdapter.onStart();

    }

    @Override
    public void onStop() {
        //结束轮播
        detailsAdapter.onStop();
        super.onStop();
    }

    @OnClick({R.id.tv_add_car_bg, R.id.iv_details_share, R.id.tv_add_car})
    public void onClick(View view) {
        switch (view.getId()) {
            //加入购物车
            case R.id.tv_add_car:
                if (Utils.isFastClick()){
                if (EmptyUtil.isEmpty(APP_TOKEN)){
                    Intent intent = new Intent(this, OneLoginMainActivity.class);
                    startActivity(intent);
                    return;
                }

                if (null != dataBean) {
                    if (dataBean.getWholesale_activities().getType()==0){//无活动商品
                        if (dataBean.getShopInfo().getIs_close() == 1||dataBean.getStoreInfo().getStock()==0) {
                            Toast.makeText(this, "此商品已售罄", Toast.LENGTH_SHORT).show();
                        }else {
                            addCart(view);
                        }
                    }else if (dataBean.getWholesale_activities().getType()==1){//一元限购活动商品
                        if (dataBean.getShopInfo().getIs_close() == 1||dataBean.getStoreInfo().getStock()==0) {
                            Toast.makeText(this, "此商品已售罄", Toast.LENGTH_SHORT).show();
                        }else {
                            addCart(view);
                        }
                    }else if (dataBean.getWholesale_activities().getType()==2){//限购活动商品
                        if (dataBean.getShopInfo().getIs_close() == 1||dataBean.getWholesale_activities().getLimit_purchase().getStock()==0) {
                            Toast.makeText(this, "此商品已售罄", Toast.LENGTH_SHORT).show();
                        }else {
                            addCart(view);
                        }
                    }else if (dataBean.getWholesale_activities().getType()==3){//秒杀活动商品
                        if (dataBean.getShopInfo().getIs_close() == 1||dataBean.getWholesale_activities().getLimit_time_good().getStock()==0) {
                            Toast.makeText(this, "此商品已售罄", Toast.LENGTH_SHORT).show();
                        }else {
                            addCart(view);
                        }
                    }
                }}
                break;
            case R.id.tv_add_car_bg:
                if (Utils.isFastClick()){
                if (EmptyUtil.isEmpty(APP_TOKEN)){
                    Intent intent = new Intent(this, OneLoginMainActivity.class);
                    startActivity(intent);
                    return;
                }

                if (null != dataBean) {
                    if (dataBean.getWholesale_activities().getType()==0){//无活动商品
                        if (dataBean.getShopInfo().getIs_close() == 1||dataBean.getStoreInfo().getStock()==0) {
                            Toast.makeText(this, "此商品已售罄", Toast.LENGTH_SHORT).show();
                        }else {
                            buyNow();
                        }
                    }else if (dataBean.getWholesale_activities().getType()==1){//一元限购活动商品
                        if (dataBean.getShopInfo().getIs_close() == 1||dataBean.getStoreInfo().getStock()==0) {
                            Toast.makeText(this, "此商品已售罄", Toast.LENGTH_SHORT).show();
                        }else {
                            buyNow();
                        }
                    }else if (dataBean.getWholesale_activities().getType()==2){//限购活动商品
                        if (dataBean.getShopInfo().getIs_close() == 1||dataBean.getWholesale_activities().getLimit_purchase().getStock()==0) {
                            Toast.makeText(this, "此商品已售罄", Toast.LENGTH_SHORT).show();
                        }else {
                            buyNow();
                        }
                    }else if (dataBean.getWholesale_activities().getType()==3){//秒杀活动商品
                        if (dataBean.getShopInfo().getIs_close() == 1||dataBean.getWholesale_activities().getLimit_time_good().getStock()==0) {
                            Toast.makeText(this, "此商品已售罄", Toast.LENGTH_SHORT).show();
                        }else {
                            buyNow();
                        }
                    }

                }}
                break;
            case R.id.iv_details_share://分享
                if (Utils.isFastClick()){
                //解決微信登录和友盟分享sdk回调冲突问题,调用友盟分享时候需要重新设置微信参数
                PlatformConfig.setWeixin(Constants.WX_APPID, Constants.WX_SECRET);
                if (shard_PW == null) {
                    shard_PW = new ShopCarPopupWindow(this, R.layout.pw_shard);
                    shard_PW.getRootView().findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            shard_PW.shareClose();
                        }
                    });
                    /**点击分享微信*/
                    shard_PW.getRootView().findViewById(R.id.ll_wechat_firend).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            //Log.e("shareToXcc","shareToXcc");
                            if (Utils.isFastClick()) {
                                shareToXcc(dataBean.getStoreInfo().getImage(), dataBean.getStoreInfo().getTitle()
                                        , dataBean.getStoreInfo().getTitle(), dataBean.getStoreInfo().getId() + "");
                            }
                        }
                    });

                    /**点击分享朋友圈*/
                    shard_PW.getRootView().findViewById(R.id.ll_wechat_pyq).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            ToastUtils.s(XFDGoodsDeatailsActivity.this, "商品和店铺分享小程序目前只支持微信好友分享哦");
                        }
                    });


                }
                shard_PW.showPopupWindow();}
                break;


        }

    }

    /**立即购买方法调用*/
    private void buyNow() {
        if (dataBean == null) {
            return;
        }
//        if (dataBean.getProductValue().size()>1) {
//            showPW();
//        }
//        }else {
            is_new = 1;
            if (dataBean.getShopInfo().getIs_self_store()==1){
                mPresenter.addCar(is_new + "", "", dataBean.getStoreInfo().getId() + "", dataBean.getIs_support()+"");
            }else {
                mPresenter.addCar(is_new + "", "", dataBean.getStoreInfo().getId() + "", "1");
            }
//        }
    }

    /**加入购物车方法*/
    private void addCart(View view) {
        is_new = 0;
        if (dataBean.getShopInfo().getIs_self_store()==1) {
            if (dataBean.getAdd_cart_num()>=dataBean.getIs_support()){
                mPresenter.addCar(is_new + "", "", dataBean.getStoreInfo().getId() + "", "1");
            }else {
                mPresenter.addCar(is_new + "", "", dataBean.getStoreInfo().getId() + "", dataBean.getIs_support()+"");
            }
        }else {
            mPresenter.addCar(is_new + "", "", dataBean.getStoreInfo().getId() + "", "1");
        }
        ShoppingCartAnimationView shoppingCartAnimationView = new ShoppingCartAnimationView(this);
        int postion[] = new int[2];
        view.getLocationInWindow(postion);
        shoppingCartAnimationView.setStartPosition(new Point(postion[0], postion[1]));
        ViewGroup rootView = (ViewGroup) getWindow().getDecorView();
        rootView.addView(shoppingCartAnimationView);
        int endPosition[] = new int[2];
        ivShopCar.getLocationInWindow(endPosition);
        shoppingCartAnimationView.setEndPosition(new Point(endPosition[0], endPosition[1]));
        shoppingCartAnimationView.startBeizerAnimation();
    }

    /**
     * 展示规格
     */
    private void showPW() {

        if (add_car_bg_PW == null) {
            add_car_bg_PW = new ShopCarPopupWindow(this, R.layout.pw_add_car_bg);
            add_car_bg_PW.setFocusable(true);
//            add_car_bg_PW.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
            add_car_bg_PW.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
            add_car_bg_PW.getRootView().findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    add_car_bg_PW.shareClose();
                }
            });
            add_car_bg_PW.getRootView().findViewById(R.id.sv_popup_root).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                }
            });
            //弹出框加入购物车
            add_car_bg_PW.getRootView().findViewById(R.id.tv_add_car).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (Utils.isFastClick()){
                    if (EmptyUtil.isEmpty(APP_TOKEN)){
                        Intent intent = new Intent(XFDGoodsDeatailsActivity.this, OneLoginMainActivity.class);
                        startActivity(intent);
                        return;
                    }
                    if (totalNum != 0) {
                        //Todo
                        // 规格逻辑不对，等后台改,注释的不删除，以后用
                        String uniqueId = "";
                        String num = "";
                        for (XFDGoodsDetailsBeen.DataBean.ProductValueBean valueBean : dataBean.getProductValue()) {
                            if (valueBean.getNum() != 0) {
                                uniqueId = valueBean.getUnique();
                                num = valueBean.getNum() + "";
                            }
                        }
                        is_new = 0;
                        mPresenter.addCar(is_new + "", uniqueId, dataBean.getStoreInfo().getId() + "", num);
                    } else {
                        Toast.makeText(mContext, "请选择商品数量", Toast.LENGTH_SHORT).show();
                    }
                }}
            });
            //立即订购
            add_car_bg_PW.getRootView().findViewById(R.id.tv_buy).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (Utils.isFastClick()){
                    if (EmptyUtil.isEmpty(APP_TOKEN)){
                        Intent intent = new Intent(XFDGoodsDeatailsActivity.this, OneLoginMainActivity.class);
                        startActivity(intent);
                        return;
                    }
                    if (totalNum != 0) {
                        add_car_bg_PW.dismiss();
                        //Todo
                        // 规格逻辑不对，等后台改,注释的不删除，以后用
                        String uniqueId = "";
                        String num = "";
                        for (XFDGoodsDetailsBeen.DataBean.ProductValueBean valueBean : dataBean.getProductValue()) {
                            if (valueBean.getNum() != 0) {
//                                if (null==valueBean.getUnique()){
//                                    uniqueId="";
//                                }else {
//                                    uniqueId = valueBean.getUnique();
//                                }
                                num = valueBean.getNum() + "";
                            }
                        }
                        is_new = 1;
                        mPresenter.addCar(is_new + "", uniqueId, dataBean.getStoreInfo().getId() + "", num);

                    } else {
                        Toast.makeText(mContext, "请选择商品数量", Toast.LENGTH_SHORT).show();
                    }
                }}
            });

            RoundedCorners roundedCorners = new RoundedCorners(20);
            //通过RequestOptions扩展功能,override:采样率,因为ImageView就这么大,可以压缩图片,降低内存消耗
            RequestOptions options = RequestOptions.bitmapTransform(roundedCorners).override(200, 200);
            options.placeholder(R.drawable.icon_defult)//图片加载出来前，显示的图片
                    .fallback(R.drawable.icon_defult) //url为空的时候,显示的图片
                    .error(R.drawable.icon_defult);
            Glide.with(this).load(dataBean.getStoreInfo().getImage()).apply(options.transform(new CenterCrop(), roundedCorners)).into((ImageView) add_car_bg_PW.getRootView().findViewById(R.id.iv_image));
            ((TextView) add_car_bg_PW.getRootView().findViewById(R.id.tv_goods_name)).setText(dataBean.getStoreInfo().getTitle());
            //TODO 这块不能删除，以后用
//            double minMoney = 0;
//            double maxMoney = 0;
//            if (dataBean.getProductValue().size() > 1) {
//                minMoney = Double.parseDouble(dataBean.getProductValue().get(0).getPrice());
//                maxMoney = Double.parseDouble(dataBean.getProductValue().get(0).getPrice());
//                for (XFDGoodsDetailsBeen.DataBean.ProductValueBean productValueBean : dataBean.getProductValue()) {
//                    double temlp = Double.parseDouble(productValueBean.getPrice());
//                    if (minMoney > temlp) {
//                        minMoney = temlp;
//                    }
//                    if (maxMoney < temlp) {
//                        maxMoney = temlp;
//                    }
//                }
//                ((TextView) add_car_bg_PW.getRootView().findViewById(R.id.tv_price)).setText("¥" + minMoney + "-" + "¥" + maxMoney);
//            } else {
//                for (int k = 0; k < 12; k++) {
//                    XFDGoodsDetailsBeen.DataBean.ProductValueBean productValueBean = new XFDGoodsDetailsBeen.DataBean.ProductValueBean();
//
//                    dataBean.getProductValue().add(productValueBean);
//                }
//                if (dataBean.getProductValue().size() != 0) {
//                    ((TextView) add_car_bg_PW.getRootView().findViewById(R.id.tv_price)).setText("¥" + dataBean.getProductValue().get(0).getPrice());
//                }
//            }
            if (Double.parseDouble(dataBean.getStoreInfo().getDiscount_price()) == 0) {
                ((TextView) add_car_bg_PW.getRootView().findViewById(R.id.tv_price)).setText("¥"+dataBean.getStoreInfo().getPrice());
            } else {
                ((TextView) add_car_bg_PW.getRootView().findViewById(R.id.tv_price)).setText("¥"+dataBean.getStoreInfo().getDiscount_price());
            }

            RecyclerView rvGoodsGuige = add_car_bg_PW.getRootView().findViewById(R.id.rv_goods_guige);
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
            linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            rvGoodsGuige.setLayoutManager(linearLayoutManager);
            //数量不大于1
            if (!(dataBean.getProductValue().size()>1)) {
                for (XFDGoodsDetailsBeen.DataBean.ProductValueBean productValueBean : dataBean.getProductValue()) {
                    productValueBean.setNum(1);
                    totalNum++;
                }
            }
            XFDShopAddCarAdapter xfdShopAddCarAdapter = new XFDShopAddCarAdapter(this, dataBean.getProductValue());
            xfdShopAddCarAdapter.setOnTotalNumListener(new TotalNumListener() {
                @Override
                public void onTotalNumListener() {
                    totalNum = 0;
                    for (XFDGoodsDetailsBeen.DataBean.ProductValueBean pvBeen : dataBean.getProductValue()) {
                        totalNum += pvBeen.getNum();
                    }
//                    Toast.makeText(mContent,totalNum + "", Toast.LENGTH_SHORT).show();
                }
            });
            rvGoodsGuige.setAdapter(xfdShopAddCarAdapter);
        }
        add_car_bg_PW.showPopupWindow();
    }

    @Override
    public void showLoading() {
        if (!ProgressDialog.getInstance().materialDialog.isShowing()) {
            ProgressDialog.getInstance().show(this);
        }
    }

    @Override
    public void hideLoading() {

            ProgressDialog.getInstance().dismiss();

    }

    @Override
    public void onError(Throwable throwable) {

    }

    @OnClick({R.id.iv_good_back, R.id.iv_shop_car})
    public void Onclick(View view) {
        switch (view.getId()) {
            case R.id.iv_good_back:
                finish();
                break;
            case R.id.iv_shop_car:
                if (Utils.isFastClick()){
                if (EmptyUtil.isEmpty(APP_TOKEN)){
                    Intent intent = new Intent(XFDGoodsDeatailsActivity.this, OneLoginMainActivity.class);
                    startActivity(intent);
                    return;
                }
                //购物车 跳转
                Intent intent = new Intent(this, GoodCarActivity.class);
                intent.putExtra("type", 1);
                startActivity(intent);}
                break;
            case R.id.iv_details_share:
                Toast.makeText(this, "点击了批发分享", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    @Override
    public void onInitDataSuccess(XFDGoodsDetailsBeen bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            detailsAdapter.setData(bean.getData());
            tvShop.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Utils.isFastClick()) {
                        Intent intent = new Intent(mContext, XFDShopDetailsActivity.class);
                        intent.putExtra("shop_id", bean.getData().getShopInfo().getId() + "");
                        mContext.startActivity(intent);
                    }
                }
            });
            tvPhone.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Utils.isFastClick()) {
                        Intent intent = new Intent(Intent.ACTION_DIAL);
                        Uri data = Uri.parse("tel:" + bean.getData().getShopInfo().getMobile());
                        intent.setData(data);
                        startActivity(intent);
                    }
                }
            });
            dataBean = bean.getData();
            //请求店铺评价接口
            Map<String,Object> map = new HashMap<>();
            map.put("storeId",dataBean.getShopInfo().getId()+"");
            map.put("limit",1);
            map.put("page",1);
            map.put("goodsId",good_id);
            map.put("isContent",1);
            mPresenter.getShopRemakeMarket(map);
            initDate();//请求店铺推荐

            if (dataBean.getWholesale_activities().getType()==0){//无活动商品
                if (dataBean.getShopInfo().getIs_close() == 1||dataBean.getStoreInfo().getStock()==0) {
                    tvAddCar.setBackgroundResource(R.drawable.order_immediately_bg_hui);
                    tvAddCarBg.setBackgroundResource(R.drawable.xfd_add_car_bg_hui);
                }
            }else if (dataBean.getWholesale_activities().getType()==1){//一元限购活动商品
                if (dataBean.getShopInfo().getIs_close() == 1||dataBean.getStoreInfo().getStock()==0) {
                    tvAddCar.setBackgroundResource(R.drawable.order_immediately_bg_hui);
                    tvAddCarBg.setBackgroundResource(R.drawable.xfd_add_car_bg_hui);
                }
            }else if (dataBean.getWholesale_activities().getType()==2){//限购活动商品
                if (dataBean.getShopInfo().getIs_close() == 1||dataBean.getWholesale_activities().getLimit_purchase().getStock()==0) {
                    tvAddCar.setBackgroundResource(R.drawable.order_immediately_bg_hui);
                    tvAddCarBg.setBackgroundResource(R.drawable.xfd_add_car_bg_hui);
                }
            }else if (dataBean.getWholesale_activities().getType()==3){//秒杀活动商品
                if (dataBean.getShopInfo().getIs_close() == 1||dataBean.getWholesale_activities().getLimit_time_good().getStock()==0) {
                    tvAddCar.setBackgroundResource(R.drawable.order_immediately_bg_hui);
                    tvAddCarBg.setBackgroundResource(R.drawable.xfd_add_car_bg_hui);
                }
            }

            dataBean.getProductValue().clear();
            XFDGoodsDetailsBeen.DataBean.ProductValueBean valueBean = new XFDGoodsDetailsBeen.DataBean.ProductValueBean();
            valueBean.setNum(0);
            valueBean.setProduct_id(dataBean.getStoreInfo().getId() + "");
            valueBean.setPrice(dataBean.getStoreInfo().getPrice());
            valueBean.setSuk(dataBean.getStoreInfo().getTitle());
            dataBean.getProductValue().add(valueBean);
            if (dataBean.isIs_coll() == false){//未收藏
                detailsAdapter.setCollectionState(false);
            }else {
                detailsAdapter.setCollectionState(true);
            }

        } else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onAddCarSuccess(ConfirmGoodBeen bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            if (add_car_bg_PW != null) {
                if (add_car_bg_PW.isShowing()) {
                    add_car_bg_PW.shareClose();
                }
            }
            if (is_new == 0) {
                if (tvCarNum.getVisibility() != View.VISIBLE) {
                    tvCarNum.setVisibility(View.VISIBLE);
                }
                UtilsData.getPreference(this, "carCount").put("car_pf_count", bean.getData().getCount().getPfcount());
                tvCarNum.setText(bean.getData().getCount().getPfcount() + "");
                Toast.makeText(this, "加入购物车成功", Toast.LENGTH_SHORT).show();
                EventBus.getDefault().post(new HomeFlushCarData());

            } else {
                Intent intent = new Intent(mContext, XFDConfirmOrderActivity.class);
                intent.putExtra("data", bean.getData());

                startActivity(intent);
            }
        } else {
            if (bean.getStatus() == Constants.LOGIN_CODE) {
                UtilsData.getPreference(this, "login").remove("head_url");
                UtilsData.getPreference(this, "login").remove("nickname");
                UtilsData.getPreference(this, "login").remove("is_store");
                UtilsData.getPreference(this, "login").remove("token");
                APP_TOKEN = "";
                Intent intent = new Intent(this, OneLoginMainActivity.class);
                startActivity(intent);
                return;
            }
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onShopCarListSuccess(ShopCarListBeen bean) {
        //不是这个界面用的，零售详情用
    }

    /**
     * 批发商品详情-推荐接口
     */
    @Override
    public void getStoreGoodsListSuccess(MoreGoodsBean bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            //if (EmptyUtil.isNotEmpty(bean.getData())){
            detailsAdapter.setMoreGoodsList(bean.getData());
            // }
        } else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void getGoodsCollectionSuccess(MoreGoodsBean bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            detailsAdapter.setCollectionState(true);
            Toast.makeText(mContext, "收藏成功", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void getGoodsCancleCollectionSuccess(MoreGoodsBean bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            detailsAdapter.setCollectionState(false);
            Toast.makeText(mContext, "取消收藏", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onGetShopRemakeMarketSuccess(ShopRemakeListMarketBean bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            if (EmptyUtil.isNotEmpty(bean.getData().getReply())){
                detailsAdapter.setRemakeDate(bean.getData().getReply().get(0));
            }
        }else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onBackPressed() {
        if (add_car_bg_PW != null) {
            if (add_car_bg_PW.isShowing()) {
                add_car_bg_PW.shareClose();
                return;
            }
        }
        if (shard_PW != null) {
            if (shard_PW.isShowing()) {
                shard_PW.shareClose();
                return;
            }
        }
        if (preferential_PW != null) {
            if (preferential_PW.isShowing()) {
                preferential_PW.shareClose();
                return;
            }
        }
        if (service_PW != null) {
            if (service_PW.isShowing()) {
                service_PW.shareClose();
                return;
            }
        }
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        if (add_car_bg_PW != null) {
            if (add_car_bg_PW.isShowing()) {
                add_car_bg_PW.dismiss();
            }
            add_car_bg_PW = null;
        }
        if (shard_PW != null) {
            if (shard_PW.isShowing()) {
                shard_PW.dismiss();
            }
            shard_PW = null;
        }
        if (preferential_PW != null) {
            if (preferential_PW.isShowing()) {
                preferential_PW.dismiss();
            }
            preferential_PW = null;
        }
        if (service_PW != null) {
            if (service_PW.isShowing()) {
                service_PW.dismiss();
            }
            service_PW = null;
        }
        bitmap = null;
        super.onDestroy();
    }

    @Override
    protected boolean isUseFullScreenMode() {
        return true;
    }

    /**
     * 选择分享方式弹窗
     */
    ChooseShareTypeDialog chooseShareTypeDialog;

    public void showChoseShareTypeDialog() {

        if (chooseShareTypeDialog == null) {
            chooseShareTypeDialog = new ChooseShareTypeDialog(this);
        }

        chooseShareTypeDialog.show();

        chooseShareTypeDialog.setChoseTypeListener(new ChooseShareTypeDialog.setChoseTypeListener() {
            @Override
            public void onChoseType(int type) {

//                if (EmptyUtil.isEmpty(title)){
//                    title = "";
//                }
//                if (EmptyUtil.isEmpty(price)){
//                    price = "";
//                }else {
//                    price = "￥"+price;
//                }
//                UMWeb web = new UMWeb(StudentApiConstants.H5_linesharegoods+goodsID+"&token="+SharedPreferencesManager.getSsotoken().
//                        substring(1,SharedPreferencesManager.getSsotoken().length()-1)+"&share="+
//                        SharedPreferencesManager.getAccountPhone());
//                web.setTitle(title);
//                web.setDescription(price);
//                web.setThumb(new UMImage(GoodsInfoActivity.this, goodsImgPath));
                if (type == 1) {//微信
                    //   shareToXcc();
//                    new ShareAction(XFDGoodsDeatailsActivity.this).withMedia(web)
//                            .setPlatform(SHARE_MEDIA.WEIXIN)
//                            .setCallback(shareListener)
//                            .share();
                } else if (type == 2) {//朋友圈

//                    new ShareAction(XFDGoodsDeatailsActivity.this).withMedia(web)
//                            .setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE)
//                            .setCallback(shareListener)
//                            .share();
                }
            }
        });
    }

    /**
     * 分享到小程序
     */
    public void shareToXcc(String imgPath, String title, String des, String shopId) {
        Glide.with(this)
                .asBitmap()
                .load(imgPath) .into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                //   bitmap = resource;
                bitmap = compressImage(resource);
                UMMin umMin = new UMMin("http://www.weixin.com");
                //兼容低版本的网页链接
                UMImage image =  new UMImage(XFDGoodsDeatailsActivity.this, bitmap);
                //image.compressStyle = UMImage.CompressStyle.SCALE;
                image.compressStyle = UMImage.CompressStyle.QUALITY;

                umMin.setThumb(image);
                // 小程序消息封面图片
                umMin.setTitle(title);
                // 小程序消息title
                umMin.setDescription(des);
                // 小程序消息描述
                umMin.setPath(Constants.XFD_GOODSINFO + shopId);//小程序页面路径
                umMin.setUserName(Constants.XCCID);
                // 小程序原始id,在微信平台查询
                new ShareAction(XFDGoodsDeatailsActivity.this)
                        .withMedia(umMin)
                        .setPlatform(SHARE_MEDIA.WEIXIN)
                        .setCallback(shareListener).share();

            }
        });

    }

    public static Bitmap compressImage(Bitmap bitmap){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        //质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        bitmap.compress(Bitmap.CompressFormat.JPEG, 60, baos);
        int options = 60;
        //循环判断如果压缩后图片是否大于50kb,大于继续压缩
        while ( baos.toByteArray().length / 1024>500) {
            //清空baos
            baos.reset();
            bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);
            options -= 10;//每次都减少10
        }
        //把压缩后的数据baos存放到ByteArrayInputStream中
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        //把ByteArrayInputStream数据生成图片
        Bitmap newBitmap = BitmapFactory.decodeStream(isBm, null, null);
        return newBitmap;
    }

    private UMShareListener shareListener = new UMShareListener() {
        /**
         * @descrption 分享开始的回调
         * @param platform 平台类型
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {
            Log.e("platform", "点击分享" + platform.getName());
        }

        /**
         * @descrption 分享成功的回调
         * @param platform 平台类型
         */
        @Override
        public void onResult(SHARE_MEDIA platform) {
            // Toast.makeText(mActivity,"成功了",Toast.LENGTH_LONG).show();
        }

        /**
         * @descrption 分享失败的回调
         * @param platform 平台类型
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            // Toast.makeText(XFDGoodsDeatailsActivity.this,"失败"+t.getMessage(),Toast.LENGTH_LONG).show();
        }

        /**
         * @descrption 分享取消的回调
         * @param platform 平台类型
         */
        @Override
        public void onCancel(SHARE_MEDIA platform) {
            //Toast.makeText(XFDGoodsDeatailsActivity.this,"取消了",Toast.LENGTH_LONG).show();

        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }
}
